package com.attendance.sz.service;


import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

import com.attendance.sz.utils.MyApplication;
import com.attendance.sz.utils.Session;
import com.attendance.sz.utils.SwipeAction;
import com.hwangjr.rxbus.RxBus;
import com.yc.nfc.CardInfo;
import com.yc.nfc.Convert;
import com.yc.nfc.NfcClient;
import com.yc.pos.SocketClient;

import java.io.IOException;
import java.math.BigInteger;
import java.security.InvalidParameterException;


/**
 * Created by Administrator on 2016-04-13.
 */
public class CheckCardExistService extends Service {
    private static final String LOGTAG = "CheckCardExistService";
    public static NfcClient client;
    CardSever cardsever;
    SocketClient socketClient;
    byte mSector;
    byte[] mKeys;
    public static boolean fig = true;

    @Override
    public void onCreate() {
        Log.d(LOGTAG, "------------onCreate-------------------");
        Handler handler = new Handler();
        socketClient = new SocketClient(getApplicationContext(), handler);
        mKeys = Convert.HexToByteArr(Session.getCarKey());

        //16419e5509b4
        mSector = (byte) Integer.parseInt(Session.getCarSection());

//        WatchDogNative.closedev();
//        fig = WatchDogNative.opendev();
//        Log.d("TAG", "mSector:" + mSector);
//        Log.d("TAG", "Session.getCarKey:" + Session.getCarKey());
//        Log.d("TAG", "mKeys2:" + mKeys[1]);
//        Log.d("TAG", "mKeys3:" + mKeys[2]);
//        Log.d("TAG", "mKeys4:" + mKeys[3]);
//        Log.d("TAG", "mKeys5:" + mKeys[4]);
//        Log.d("TAG", "mKeys6:" + mKeys[5]);

//        if (fig) {
//            Dog dog = new Dog();
//            dog.start();
//        } else {
////            WatchDogNative.closedev();
//        }

       /* if ("3".equals(Session.getCom())) {
            if (client == null)
                client = new NfcClient(Integer.parseInt(Session.getCom()), mSector, mKeys);
            try {
                client.open();
            } catch (InvalidParameterException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    socketClient.addUpdatTimeCommand();
                }
            }, 1000 * 10);
            if (cardsever == null)
                cardsever = new CardSever();
            cardsever.start();
        }*/
    }

    @Override
    public void onStart(Intent intent, int startId) {
        Log.d(LOGTAG, "------------onStart-------------------");
        bRun = true;
    }

    @Override
    public void onDestroy() {
        Log.d(LOGTAG, "------------onDestroy-------------------");
        if (socketClient != null) {
            socketClient.CloseSocket();
        }
        try {
            bRun = false;
            if ("3".equals(Session.getCom()) && cardsever != null) {
                cardsever.interrupt();
                client.close();
            }

        } catch (Exception ex) {

        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onRebind(Intent intent) {
    }

    static boolean bRun = true;

    public static void startAttendance() {
        bRun = true;
    }

    public static void stopAttendance() {
        bRun = false;
        fig = false;
    }

    class CardSever extends Thread {
        public CardSever() {
            // TODO Auto-generated constructor stub
        }

        @Override
        public void run() {
            super.run();
            while (true) {
                if (bRun) {
                    if (client.isOpen()) {
                        CardInfo info = client.read();
//                        client.readName();
                        if (info != null) {
                            RxBus.get().post(SwipeAction.Attendance, info);

                        } else if (MyApplication.getInstance().getgstrDestIP().equals("1") || MyApplication.getInstance().getgstrDestIP().equals("2")) {
                           // RxBus.get().post(SwipeAction.UpdateDeviceNo, "1");

                        } else if (MyApplication.getInstance().getgstrDestIP().equals("0")) {
                           // RxBus.get().post(SwipeAction.GetCardParam, "");

                        }   else if (MyApplication.getInstance().getgstrDestIP().equals("6")){
                            Log.d("TAG","相等");
                        }else if (MyApplication.getInstance().getgstrDestIP().equals("111")) {
                            MyApplication.getInstance().setgstrDestIP("0");
                            try {
                                Log.d("TTT","111Auth");
                                RxBus.get().post("Auth", "");

                                Thread.sleep(1000);//防止 连续 操作
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
//                     bRun=false;
//                        return;
                    }
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }


            }
        }


    }

    class Dog extends Thread {
        @Override
        public void run() {
            super.run();
            while (true) {
                if (fig) {
//                    WatchDogNative.writedev();
//
//                    Log.d("TAG", "执行");
//                    try {
//                        Thread.sleep(3000);
//                        if (MyApplication.getApp().getgstrDestIP().equals("6")){
//                            MyApplication.getInstance().setCard("1");
//                        }
//                        Log.d("TAG", "睡眠");
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
                }
            }


        }
    }

    public static String card(byte[] cardID) {
        String hex = Convert.ByteArrToHex(cardID, null);
        BigInteger id = new BigInteger(hex, 16);
        return String.valueOf(id.longValue());
    }

}
